<script lang="ts" setup>
import { ref } from 'vue'
import { register } from '@/api/login'
import BaseButton from '@/components/ui/BaseButton.vue'
import BaseCard from '@/components/ui/BaseCard.vue'
import { useUserStore } from '@/store/user'
import { showSuccessMessage, showValidationError, validateRegisterForm } from '@/utils/formValidation'
import { smartNavigationBack } from '@/utils/navigation'
import { safeAreaInsets } from '@/utils/systemInfo'

defineOptions({
  name: 'AuthRegister',
})

definePage({

  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '注册',
  },
})

// 用户store
const userStore = useUserStore()

// 注册表单数据
const registerForm = ref({
  username: '',
  nickname: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreement: false,
})

// 加载状态
const loading = ref(false)

// 处理注册
async function handleRegister() {
  const { username, nickname, email, password, confirmPassword, agreement } = registerForm.value

  // 使用表单验证工具
  const validationResult = validateRegisterForm(username, nickname, email, password, confirmPassword, agreement)
  if (!validationResult.isValid) {
    showValidationError(validationResult)
    return
  }

  loading.value = true

  try {
    // 调用注册API
    const registerData = {
      username,
      password,
      confirmPassword,
      nickname: nickname || undefined, // 如果昵称为空则不传
      email: email || undefined, // 如果邮箱为空则不传
      phone: undefined, // 手机号暂时不传
    }

    const response = await register(registerData)

    showSuccessMessage('注册成功！欢迎加入')

    // 注册成功后跳转到登录页面，让用户重新登录
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/auth/login/index',
      })
    }, 1500)
  }
  catch (error: any) {
    console.error('注册失败:', error)

    // 根据不同的错误类型显示不同的错误信息
    let errorMessage = '注册失败，请重试'
    if (error.data?.message) {
      errorMessage = error.data.message
    }
    else if (error.status === 409) {
      errorMessage = '用户名已存在，请换个用户名'
    }
    else if (error.status === 400) {
      errorMessage = '输入信息有误，请检查后重试'
    }

    uni.showToast({
      title: errorMessage,
      icon: 'error',
      duration: 3000,
    })
  }
  finally {
    loading.value = false
  }
}

// 智能返回导航
function handleNavigationBack() {
  smartNavigationBack('/pages/index/index', {
    successCallback: () => {
      console.log('导航成功')
    },
    failCallback: () => {
      console.error('导航失败')
    },
  })
}

// 跳转到登录页面
function goToLogin() {
  uni.navigateTo({
    url: '/pages/auth/login/index',
  })
}

// 返回按钮处理
function handleBack() {
  handleNavigationBack()
}
</script>

<template>
  <view class="auth-page bg-bg-dark" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
    <!-- 顶部导航栏 -->
    <view class="auth-header">
      <view class="header-left">
        <view class="back-button" @click="handleBack">
          <i class="fas fa-chevron-left text-32rpx text-text-primary" />
        </view>
        <text class="header-title">注册</text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="page-content">
      <!-- Logo 和欢迎信息 -->
      <view class="auth-welcome">
        <view class="logo-container">
          <i class="fas fa-user-plus text-120rpx text-primary" />
        </view>
        <text class="welcome-title">加入我们</text>
        <text class="welcome-subtitle">创建您的账号，开启精彩阅读之旅</text>
      </view>

      <!-- 注册表单 -->
      <view class="auth-form">
        <BaseCard class="form-card">
          <view class="form-group">
            <text class="form-label">用户名</text>
            <input
              v-model="registerForm.username"
              type="text"
              class="form-input"
              placeholder="请输入用户名(3-20位)"
              :adjust-position="true"
              :hold-keyboard="true"
            >
          </view>
          <view class="form-group">
            <text class="form-label">昵称</text>
            <input
              v-model="registerForm.nickname"
              type="text"
              class="form-input"
              placeholder="请输入昵称（可选）"
              :adjust-position="true"
              :hold-keyboard="true"
            >
          </view>
          <view class="form-group">
            <text class="form-label">邮箱</text>
            <input
              v-model="registerForm.email"
              type="email"
              class="form-input"
              placeholder="请输入邮箱地址（可选）"
              :adjust-position="true"
              :hold-keyboard="true"
            >
          </view>

          <view class="form-group">
            <text class="form-label">密码</text>
            <input
              v-model="registerForm.password"
              type="password"
              class="form-input"
              placeholder="请输入密码（至少6位）"
              :adjust-position="true"
              :hold-keyboard="true"
            >
          </view>

          <view class="form-group">
            <text class="form-label">确认密码</text>
            <input
              v-model="registerForm.confirmPassword"
              type="password"
              class="form-input"
              placeholder="请再次输入密码"
              :adjust-position="true"
              :hold-keyboard="true"
            >
          </view>

          <view class="form-group">
            <view class="checkbox-label" @click="registerForm.agreement = !registerForm.agreement">
              <view class="custom-checkbox" :class="[{ checked: registerForm.agreement }]">
                <text v-if="registerForm.agreement" class="check-icon">✓</text>
              </view>
              <text>我已阅读并同意《用户协议》和《隐私政策》</text>
            </view>
          </view>

          <BaseButton
            variant="primary"
            class="register-btn w-full"
            :disabled="loading"
            @click="handleRegister"
          >
            <text v-if="loading">注册中...</text>
            <text v-else>注册</text>
          </BaseButton>
        </BaseCard>
      </view>

      <!-- 底部登录链接 -->
      <view class="auth-footer">
        <text class="footer-text">
          已有账号？
          <text class="link-text" @click="goToLogin">立即登录</text>
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.auth-page {
  min-height: 100vh;
}

// 顶部导航栏样式
.auth-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  background-color: var(--background-medium);
}

.header-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.back-button {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: var(--background-light);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.back-button:hover {
  background-color: var(--background-hover);
}

.header-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.page-content {
  padding: 0 var(--spacing-md);
  padding-bottom: 120rpx;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 200rpx);
}

// Logo 和欢迎信息
.auth-welcome {
  text-align: center;
  margin: var(--spacing-xl) 0;
}

.logo-container {
  margin-bottom: var(--spacing-lg);
}

.welcome-title {
  font-size: 48rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: var(--spacing-sm);
}

.welcome-subtitle {
  font-size: 28rpx;
  color: var(--text-secondary);
  display: block;
  line-height: 1.4;
}

// 表单样式
.auth-form {
  flex: 1;
}

.form-card {
  padding: var(--spacing-lg);
}

.form-group {
  margin-bottom: var(--spacing-md);
}

.form-label {
  font-size: 28rpx;
  color: var(--text-secondary);
  margin-bottom: var(--spacing-sm);
  display: block;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 var(--spacing-md);
  background-color: var(--background-light);
  border: 2rpx solid var(--border-color);
  border-radius: var(--border-radius);
  color: var(--text-primary);
  font-size: 28rpx;
  box-sizing: border-box;
  -webkit-appearance: none;
  line-height: 80rpx;
}

.form-input::placeholder {
  color: var(--text-muted);
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.checkbox-label {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-sm);
  color: var(--text-secondary);
  font-size: 28rpx;
  cursor: pointer;
  line-height: 1.4;
}

.custom-checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid var(--border-color);
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--background-light);
  transition: all 0.2s ease;
  flex-shrink: 0;
  margin-top: 4rpx;
}

.custom-checkbox.checked {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.check-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.register-btn {
  margin-top: var(--spacing-md);
}

// 底部样式
.auth-footer {
  text-align: center;
  margin-top: var(--spacing-lg);
}

.footer-text {
  font-size: 28rpx;
  color: var(--text-muted);
}

.link-text {
  color: var(--primary-color);
  font-weight: 500;
  cursor: pointer;
}
</style>
